//js的对象
//写法跟java类似
const express = require('express');
const ResObj = require('../utils/ResObj');
const { Op } = require('sequelize');

class baserouter {

    //构造函数
    constructor(model) {
        this.model = model;
        this.router = express.Router();
        //要记得去注册方法
        this.add();//新增
        this.list();//分页
        this.find();//查找
        this.update();//根据主键修改
        this.delete();//删除

    }

    //获取模型
    getModel() {
        return this.model;
    }

    //获取router对象
    getRouter() {
        return this.router;
    }

    //这里面的方法不需要写function
    add() {
        //新增用户
        this.router.post("/add", (req, res) => {
            let data = req.body;
            try {
                let result = this.getModel().create(data);
                res.end(ResObj.success(result))
            } catch (error) {
                console.log(error)
                res.end(ResObj.fail(400, error.message))
            }
        })
    }


    //查询单个数据
    find() {
        this.router.get("/find", async (req, res) => {
            let id = req.query.id ? req.query.id : null;
            if (id == null) {
                res.end(ResObj.fail(4001, '参数错误'));
            } else {
                let data = await this.getModel().findByPk(id)
                res.end(ResObj.success(data));
            }
        })
    }


    //修改数据
    update() {
        this.router.post("/update", async (req, res) => {
            //获取要修改的数据
            let updateData = req.body;
            if (updateData.where == undefined) {
                res.end(ResObj.fail(4001, "where不能为空"))
                return;
            }
            if (updateData.condition == undefined) {
                res.end(ResObj.fail(4001, "condition不能为空"))
                return;
            }
            let where = JSON.parse(updateData.where);
            let condition = JSON.parse(updateData.condition);

            //查询出要修改的数据
            try {
                this.getModel().update(condition, {
                    where: where
                });
                res.end(ResObj.success(''))
            } catch (error) {
                console.log(error)
                res.end(ResObj.fail(400, JSON.stringify(error)))
            }
        })
    }

    //分页查询
    //有条件时类似 http://localhost:8080/user/list?where={"key":"工程师","column":"direction","type":"like"}
    list() {
        //分页查询 select * from tablenam where  limit (page-1)*pageSize,pageSize
        this.router.get("/list", async (req, res) => {
            let params = req.query;
            let page = params.page != undefined ? Number(params.page) : 1;
            let pageSize = params.pageSize != undefined ? Number(params.pageSize) : 20;
            //规定传参的格式 where={key:工程师,column:'name,diection',type:'like'},key也就是 where的value值是个字符串,key 查询刺 type就是处理类型eq 相对 like
            //就是模糊查询
            try {
                let where = params.where != undefined ? params.where : {};
                let type = typeof (where);
                if (type != "object") {//说明有查询条件
                    let condition = JSON.parse(where);
                    let column = condition.column;
                    let columnArr = column.split(",");
                    where = {};//把where变更为一个对象
                    for (let tem of columnArr) {
                        console.log(tem);
                        if (condition.type == "like") {
                            where[tem] = {
                                [Op.like]: '%' + condition.key + '%'
                            }
                        }
                        if (condition.type == "eq") {
                            where[tem] = {
                                [Op.eq]: condition.key
                            }
                        }
                    }
                }
                const { count, rows } = await this.getModel().findAndCountAll({
                    where: where,
                    offset: (page - 1) * pageSize,
                    limit: pageSize
                });
                let data = { total: count, list: rows };
                res.end(ResObj.success(data));
            } catch (error) {
                console.log(error)
                res.end(ResObj.fail(4001, error.message));
            }

        })
    }

    //删除数据
    delete() {
        this.router.post("/delete", async (req, res) => {
            //获取要修改的数据
            let deleteData = req.body;
            if (deleteData.where == undefined) {
                res.end(ResObj.fail(4001, "where不能为空"))
                return;
            }
            let where = JSON.parse(deleteData.where);
            //查询出要修改的数据
            try {
                this.getModel().destroy({
                    where: where
                });
                res.end(ResObj.success(''))
            } catch (error) {
                console.log(error)
                res.end(ResObj.fail(400, JSON.stringify(error)))
            }
        })
    }
}

module.exports = baserouter;